<?php


namespace app\api\controller;


use app\api\validate\GiftChose;
use app\common\controller\Api;
use app\common\model\SelfAddress;
use app\common\model\Gift as GiftModel;
use app\common\model\UserAddress;
use think\Config;
use think\Db;
use think\exception\ValidateException;

/**
 * 礼盒列表
 */
class Gift extends Api
{

    protected function redis()
    {
        $redis =  new \Redis();
        $redis->connect('127.0.0.1');
        return $redis;
    }

    /**
     * 礼盒列表
     */
    public function list()
    {
        $redis = $this->redis();
        $data = $redis->get('gift_list');
        if (!$data) {
            $data = GiftModel::field('id, name, img')->select();
            $data = serialize($data);
            $redis->set('gift_list', $data);
        }
        $data = $data ? unserialize($data) : [];
        $this->success('', $data);
    }

    /**
     * 礼盒内容
     * @param int $id 礼盒id
     */
    public function content()
    {
        $id = input('id');
        $redis = $this->redis();
        $data = $redis->get('gift_content_'.$id);
        if (!$data) {
            $data = GiftModel::where(['id'=>$id])
                ->with('content')
                ->field('id, detail_img as img')
                ->find();
            $data = serialize($data);
            $redis->set('gift_content_'.$id, $data);
        }
        $data = $data ? unserialize($data) : [];
        $this->success('', $data);
    }

    /**
     * 自提城市列表
     */
    public function self_city()
    {
        $redis = $this->redis();
        $data = $redis->get('self_city');
        if (!$data) {
            $data = SelfAddress::distinct(true)->column('city');
            $data = serialize($data);
            $redis->set('self_city', $data);
        }
        $data = $data ? unserialize($data) : [];
        $this->success('', $data);
    }

    /**
     * 自提地址列表
     * @param string $city 城市
     */
    public function self_address()
    {
        $city = input('city');
        $redis = $this->redis();
        $data = $redis->get('self_address_'.$city);
        if (!$data) {
            $data = SelfAddress::where('city', $city)->field('id,address')->select();
            $data = serialize($data);
            $redis->set('self_address_'.$city, $data);
        }
        $data = $data ? unserialize($data) : [];
        $this->success('', $data);
    }

    /**
     * 礼品选择
     * @ApiMethod (POST)
     * @param int $id 详情id
     * @param int $gift_id 礼盒id
     * @param int $mobile 手机号码
     * @param int $type 收获方式:1=自提,2=邮寄
     * @param int $province_id 省
     * @param int $city_id 市
     * @param int $district_id 区
     * @param int $detail 详细地址
     * @param int $self_id 自提地址id
     */
    public function chose()
    {
        $param = input('post.');
        $validate = new GiftChose();
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $user = $this->auth->getUser();
        $id = input('post.id');
        if (!$id) {
            //报名截止
            $sign_up = Config::get('site.sign_up');
            if ($sign_up) {
                $end_time = strtotime($sign_up);
                if (time() > $end_time) {
                    $this->error('已超过报名时间');
                }
            }
            if ($user['exchange']) {
                $this->error('您已完成兑换,无法重复兑换');
            }
        } else {
            $select_end = Config::get('site.select_end');
            if ($select_end) {
                $end_time = strtotime($select_end);
                if (time() > $end_time) {
                    $this->error('已超过更改收货方式截止时间');
                }
            }
        }

        unset($param['id']);
        Db::startTrans();
        try {
            $param['user_id'] = $this->auth->id;
            $address = new UserAddress();
            if (!$id) {
                $user->exchange = 1;
                $user->exchangetime = time();
                $user->save();
                $address->allowField(true)->save($param);
            } else {
                $address->allowField(true)->save($param, ['id'=>$id]);
            }

            Db::commit();
        } catch (ValidateException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('');
    }

    /**
     * 没选的默认一
     */
    public function set_default()
    {
        $user = \app\common\model\User::where('exchange', 0)->field('id')->select();
        $update_user = [];
        $update_address = [];
        foreach ($user as $v) {
            $u['id'] = $v['id'];
            $u['exchangetime'] = time();
            $u['exchange'] = 1;
            $update_user[] = $u;
            $a['user_id'] = $v['id'];
            $a['gift_id'] = 1;
            $update_address[] = $a;
        }

        $userModel = new \app\common\model\User();
        $address = new UserAddress();
        $userModel->saveAll($update_user);
        $address->saveAll($update_address);
    }

}